package nuts.context;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import nuts.context.meta.NutsHome;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;

/**
 * This object will use XML as a defining tool to parse the nuts meta. It will
 * use the default JAXP-configured XML parser
 * 
 * @author jason
 * 
 */
public class XMLResourceLoader implements ResourceLoader {

	private String path;

	private File xsd;

	private boolean needValidate;

	public static final Log logger = LogFactory.getLog(XMLResourceLoader.class);

	/**
	 * Initialize the resource parser the path can be classpath(cp:)
	 * ,http(http:) or file(file:)
	 * 
	 * @param path
	 */
	public XMLResourceLoader(String path, boolean needValidate) {
		super();
		this.path = path;
		this.xsd = new File("/home/jason/workspace-nuts/Nuts-core/src/main/java/NutsHome.xsd");
		this.needValidate = needValidate;

	}
	
	public static void main(String[] args){
		XMLResourceLoader loader=new XMLResourceLoader("file:/home/jason/workspace-nuts/Nuts-core/src/main/java/sample.xml",true);
		try {
			loader.load();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public XMLResourceLoader(String path) {
		this(path, false);
	}

	@Override
	public synchronized NutsHome load() throws Exception {
		DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory
				.newInstance();
		logger.info(logger);
		if (logger.isDebugEnabled()) {
			logger.debug("Using JAXP provider ["
					+ documentBuilderfactory.getClass().getName() + "]");
		}
		InputStream targetStream = null;
		targetStream = getInputStream();
		if (needValidate) {
			Schema schema = SchemaFactory.newInstance(
					XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(this.xsd);
			schema.newValidator().validate(new StreamSource(targetStream));
		}

		DocumentBuilder builder = documentBuilderfactory.newDocumentBuilder();
		Document doc = builder.parse(getInputStream());
		return null;
	}

	private InputStream getInputStream() throws IOException {
		if (this.path.startsWith("cp")) {
			return XMLResourceLoader.class.getClassLoader()
					.getResourceAsStream(path.substring(3));
		}
		if (this.path.startsWith("file")) {
			return new FileInputStream(path.substring(5));
		}
		if (this.path.startsWith("http") || this.path.startsWith("https")) {
			URL url = new URL(this.path);
			return url.openStream();
		}
		return null;
	}

}
